<template>
  <div>
    <el-backtop :right="100" :bottom="200" :visibility-height="10" />
    <!-- 搜索 -->
    <el-space wrap style="margin-bottom:10px">
      <el-input v-model="title" placeholder="请输入优惠券标题" clearable style="width:200px" />
      <el-select v-model="type" placeholder="请选择优惠券类型" clearable>
        <el-option v-for="item in otype" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="status" placeholder="请选择优惠券状态" clearable>
        <el-option
          v-for="item in ostatus"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" :icon="Search" @click="listData">查找</el-button>
      <el-button type="primary" :icon="Plus" @click="Add">添加</el-button>
      <el-button type="primary" :icon="Download" @click="tableToExcel">导出当前页</el-button>
    </el-space>
    <!-- 列表 -->
    <el-table :data="tableData" border>
      <el-table-column prop="id" label="优惠券ID" align="center" />
      <el-table-column prop="title" label="优惠券名称" align="center" />
      <el-table-column prop="type" label="优惠券类型" align="center">
        <template #default="scope">{{scope.row.type==1?'满减券':'全部'}}</template>
      </el-table-column>
      <el-table-column prop="description" label="介绍" align="center" />
      <el-table-column prop="total" label="优惠券数量" align="center" />
      <el-table-column prop="limit" label=" 每人限量" align="center" />
      <el-table-column prop="discount" label="满减金额" align="center">
        <template #default="scope">减免{{scope.row.discount}}元</template>
      </el-table-column>
      <el-table-column prop="min" label="最低消费" align="center">
        <template #default="scope">满{{scope.row.min}}元可用</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag>
            {{scope.row.status==0?'下架':(scope.row.status==1?'正常':(scope.row.status==-1?'已过期':''))}}
            <!-- {{scope.row.status?hendStatus(scope.row):''}} -->
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="categoryTitle" label="使用类目名称" align="center">
        <template #default="scope">
          <el-tag v-show="scope.row.categoryTitle">{{scope.row.categoryTitle}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="categoryId" label="使用类目ID" align="center" />
      <el-table-column prop="days" label="领券相对天数" align="center">
        <template #default="scope">{{scope.row.days?scope.row.days:'无'}}</template>
      </el-table-column>
      <el-table-column prop="gmtStart" label="领券开始时间" align="center">
        <template #default="scope">
          <p v-show="scope.row.gmtStart">{{scope.row.gmtStart?timeformatT(scope.row.gmtStart):'无'}}</p>
          {{scope.row.gmtStart?timeformatS(scope.row.gmtStart):'无'}}
        </template>
      </el-table-column>
      <el-table-column prop="gmtEnd" label="领券结束时间" align="center">
        <template #default="scope">
          <p v-show="scope.row.gmtEnd">{{scope.row.gmtEnd?timeformatT(scope.row.gmtEnd):'无'}}</p>
          {{scope.row.gmtEnd?timeformatS(scope.row.gmtEnd):'无'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleStatus(scope.row)"
          >{{scope.row.status?'冻结':'激活'}}</el-button>
          <el-button size="small" type="info" @click="handleSee(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 修改弹框 -->
    <el-dialog v-model="dialogFormVisible" :title="titleF">
      <el-form
        :model="form"
        ref="ruleFormRef"
        :rules="rules"
        label-width="120px"
        label-position="left"
        :disabled="titleF=='编辑'"
      >
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择优惠券类型" clearable>
            <el-option
              v-for="item in otype"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input v-model="form.disriction" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠券数量" prop="total">
          <el-input
            oninput="value=value.replace(/[^\d]/g,'')"
            clearable
            v-model="form.total"
            placeholder="0"
          >
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限购" prop="limit">
          <el-input
            v-model="form.limit"
            placeholder="0"
            oninput="value=value.replace(/[^\d]/g,'')"
            clearable
          >
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discount ">
          <el-input
            v-model="form.discount"
            placeholder="0"
            oninput="value=value.replace(/[^\d]/g,'')"
            clearable
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="min">
          <el-input
            v-model="form.min"
            placeholder="0"
            oninput="value=value.replace(/[^\d]/g,'')"
            clearable
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择优惠券状态" clearable>
            <el-option
              v-for="item in ostatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" prop="days">
          <span>
            <el-button
              class="el-form-item-days"
              :type="daysOrtiem?'primary':''"
              @click="subMitDays"
            >领券相对天数</el-button>
            <el-button
              class="el-form-item-time"
              :type="daysOrtiem?'':'primary'"
              @click="subMitDays"
            >指定绝对时间</el-button>
          </span>
        </el-form-item>
        <el-form-item label v-show="daysOrtiem==true">
          <el-input v-model="form.days" placeholder="0">
            <template #append>天</template>
          </el-input>
        </el-form-item>
        <el-form-item label v-show="daysOrtiem==false">
          <el-config-provider :locale="locale">
            <el-date-picker
              v-model="form.gmtStart"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY/MM/DD hh:mm:ss"
              value-format="x"
            />至
            <el-date-picker
              v-model="form.gmtEnd"
              type="datetime"
              placeholder="请选择结束时间"
              format="YYYY/MM/DD hh:mm:ss"
              value-format="x"
            />
          </el-config-provider>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <span>
            <el-button
              class="el-form-item-days"
              :type="allOrappoint?'primary':''"
              @click="subMitRange"
            >全场通用</el-button>
            <el-button
              class="el-form-item-time"
              :type="allOrappoint?'':'primary'"
              @click="subMitRange"
            >指定类目</el-button>
          </span>
        </el-form-item>
        <el-form-item label=" " v-show="allOrappoint==true"></el-form-item>
        <el-form-item label="优惠类目" v-show="allOrappoint==false">
          <el-cascader
            v-model="form.categoryId"
            :options="options"
            placeholder="优惠类目"
            :props="props"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible=false">取消</el-button>
          <el-button v-show="titleF=='创建'" type="primary" @click="fangdou">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <dome v-bind="domes" @limits="limits" @pages="pages" />
  </div>
</template>
<script>
import { post } from "@/util/http";
import dome from "@/components/DomeAndTop.vue";
import { Search, Plus, Download } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import timeformatT from "../../../timeformat/formatT";
import timeformatS from "../../../timeformat/formatS";
import { ElConfigProvider } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import login from "@/store/login";
import { debounce } from "@/fangdou/fangdou";//防抖
export default {
  components: {
    dome,
    ElConfigProvider,
  },
  data() {
    return {
      Search,
      Download,
      Plus,
      locale: zhCn,
      title: "", //搜索
      type: "", //搜索
      status: "", //搜索
      tableData: [], //列表
      dialogFormVisible: false, //布尔值
      titleF: "", //表单标题
      daysOrtiem: true, //表单的领券相对天数or指定相对时间
      allOrappoint: true, //表单的全场通用or指定类目
      // 优惠类目
      options: [],
      // 分页
      domes: {
        limit: 10,
        page: 1,
        total: 10,
      },
      // 类目的配置
      props: {
        value: "id",
        label: "title",
        children: "childrenList",
        emitPath: false,
      },
      // 表单数据
      form: {
        title: "",
        type: "",
        disriction: "",
        total: "",
        limit: "",
        discount: "",
        min: "",
        status: "",
        days: "",
        categoryId: "",
        categoryTitle: "",
        gmtStart: "",
        gmtEnd: "",
      },
      //   用户状态
      otype: [
        {
          value: 1,
          label: "满减券",
        },
        {
          value: 2,
          label: "全部",
        },
      ],
      //   用户状态
      ostatus: [
        {
          value: 0,
          label: "下架",
        },
        {
          value: 1,
          label: "正常",
        },
        {
          value: "-1",
          label: "已过期",
        },
        {
          // value:'',
          label: "全部",
        },
      ],
      // 表单规则
      rules: {
        title: [
          {
            required: true,
            message: "优惠券标题不能为空",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择优惠券类型",
            trigger: "blur",
          },
        ],
        total: [
          {
            required: true,
            message: "请输入整数",
            trigger: "blur",
          },
          {
            required: true,
            min: 1,
            message: "请输入整数",
            trigger: "blur",
          },
        ],
        limit: [
          {
            required: true,
            message: "请输入整数",
            trigger: "blur",
          },
          {
            required: true,
            min: 1,
            message: "请输入整数",
            trigger: "blur",
          },
        ],
        discount: [
          {
            required: true,
            message: "请输入整数",
            trigger: "blur",
          },
          {
            required: true,
            min: 1,
            message: "请输入整数",
            trigger: "blur",
          },
        ],
        min: [
          {
            required: true,
            message: "请输入整数",
            trigger: "blur",
          },
          {
            required: true,
            min: 1,
            message: "请输入整数",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择状态",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.listData();
  },
  methods: {
    timeformatS, // 使用类目名称事件
    timeformatT, // 时间转换事件()
    //有效期---- 表单的领券相对天数or指定相对时间事件
    subMitDays() {
      this.daysOrtiem = !this.daysOrtiem; //布尔值取反----在html中使用三元函数判断，如果daysOrtiem为true的话显示领券相对天数否则就显示指定相对时间
    },
    //商品限制范围--- 表单的全场通用or指定类目事件
    subMitRange() {
      this.allOrappoint = !this.allOrappoint; //同理==布尔值取反----在html中使用三元函数判断，如果allOrappoint为true的话显示空lable标签否则就显示指定类目
    },
    hendStatus(e) {
      let time = new Date().getTime();
      if (e.gmtEnd < time) {
        e.status = "-1";
      }
      switch (e.status) {
        case 0:
          return "下架";
          break;
        case 1:
          return "正常";
          break;
        case -1:
          return "已过期";
          break;
        default:
          break;
      }
    },
    // 导出当前页
    async tableToExcel() {
      const jsonData = this.tableData; //想要导出的数据，必须是数组
      // 列标题，逗号隔开，每一个逗号就是隔开一个单元格
      let str = `优惠券ID, 优惠券名称 ,优惠券类型, 介绍 ,优惠券数量, 每人限量, 满减金额 ,最低消费 ,状态 ,使用类目名称 ,使用类目ID ,领券相对天数 ,领券开始时间 ,领券结束时间\n`;
      // 增加\t为了不让表格显示科学计数法或者其他格式
      for (let i = 0; i < jsonData.length; i++) {
        for (const key in jsonData[i]) {
          str += `${jsonData[i][key] + "\t"},`;
        }
        str += "\n";
      }
      // encodeURIComponent解决中文乱码
      const uri =
        "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
      // 通过创建a标签实现
      const link = document.createElement("a");
      link.href = uri;
      // 对下载的文件命名
      link.download = "优惠券管理.csv";
      link.click();
    },
    // 类目列表
    categoryData() {
      let data = {
        _gp: "admin.category",
        _mt: "list",
      };
      post(data)
        .then((res) => {
          if (200 == res.data.errno) {
            this.options = res.data.data.items;
          } else {
            ElMessage.warning(res.data.errmsg, "111");
          }
        })
        .catch((err) => {
          ElMessage.error(err.data.errmsg);
        });
    },
    // 提交
    subMit() {
      // 如果领券开始时间大于结束时间就会返回一个警告否则就执行下一步
      if (this.form.gmtStart > this.form.gmtEnd)
        return ElMessage.warning("领券开始时间不能大于结束时间");
      this.$refs.ruleFormRef.validate((ref) => {
        if (ref) {
          if (this.titleF == "创建") {
            let data = {
              _gp: "admin.coupon",
              _mt: "create",
              ...this.form,
            };
            post(data)
              .then((res) => {
                if (200 == res.data.errno) {
                  console.log(res, "创建成功");
                  this.form = {
                    title: "",
                    type: "",
                    disriction: "",
                    total: "",
                    limit: "",
                    discount: "",
                    min: "",
                    status: "",
                    days: "",
                    categoryId: "",
                  };
                  this.dialogFormVisible = false;
                  this.listData();
                  ElMessage.success("创建成功");
                } else {
                  ElMessage.warning(res.data.errmsg);
                }
              })
              .catch((err) => {
                ElMessage.error(err.data.errmsg);
              });
          } else {
          }
        } else {
          ElMessage.warning("带星号的必填信息不能为空!");
        }
      });
    },
    fangdou: debounce(function () {
      this.subMit();
    }),
    // 查看
    handleSee(e) {
      console.log(e, "当行数据");
      this.form = {
        title: e.title,
        type: e.type,
        disriction: e.disriction,
        total: e.total,
        limit: e.limit,
        discount: e.discount,
        min: e.min,
        status: e.status,
        days: e.days,
        gmtStart: e.gmtStart,
        gmtEnd: e.gmtEnd,
        categoryId: e.categoryId,
        categoryTitle: e.categoryTitle,
      };
      this.dialogFormVisible = true;
      this.titleF = "编辑";
      this.categoryData();
    },
    // 添加
    Add() {
      this.form = {
        title: "",
        type: "",
        disriction: "",
        total: "",
        limit: "",
        discount: "",
        min: "",
        status: "",
        days: "",
        categoryId: "",
      };
      this.dialogFormVisible = true;
      this.titleF = "创建";
      this.categoryData();
    },
    // 状态改变
    handleStatus(e) {
      //   e.status = !e.status;
      if (e.status == 1) {
        //判断当前的status如果为1就改为0，改为冻结状态
        e.status = 0;
        ElMessage.success("下架成功");
        this.Statu(e); //激活冻结请求事件----刷新
      } else if (e.status == 0) {
        //判断当前的status如果为0就改为1，改为激活状态
        e.status = 1;
        ElMessage.success("激活成功");
        this.Statu(e);
      }
    },
    // 状态改变请求
    Statu(e) {
      let data = {
        _gp: "admin.coupon",
        _mt: "updateCouponStatus",
        id: e.id,
        status: e.status,
      };
      post(data)
        .then((res) => {
          if (200 == res.data.errno) {
            // ElMessage.success("状态修改成功");
          } else {
            ElMessage.warning(res.data.errmsg);
          }
        })
        .catch((err) => {
          ElMessage.error(err.data.errmsg);
        });
    },
    listData() {
      let data = {
        _gp: "admin.coupon",
        _mt: "list",
        title: this.title,
        type: this.type,
        status: this.status,
        pageNo: this.domes.page, //当前页码
        limit: this.domes.limit, //页码长度
      };
      post(data)
        .then((res) => {
          if (200 == res.data.errno) {
            this.tableData = res.data.data.items;
            this.domes.total = res.data.data.total;
          } else {
            ElMessage.warning(res.data.errmsg);
          }
        })
        .catch((err) => {
          ElMessage.error(err.data.errmsg);
        });
    },
    limits(e) {
      this.domes.limit = e;
      this.$nextTick(()=>{
        this.listData();
      })
    },
    pages(e) {
      this.domes.page = e;             
      this.$nextTick(()=>{
        this.listData();
      })
    },
  },
};
</script>
<style lang="less" scoped>
.el-form-item {
  margin-left: 40px;
  .el-input {
    width: 450px;
  }
}
.el-form-item-days {
  border-radius: 4px 0px 0px 4px;
}
.el-form-item-time {
  border-radius: 0px 4px 4px 0px;
  margin-left: 0px;
}
</style>